/**
 * JavaScript 格式生成器
 * 生成 .js 模块文件
 */
class JsGenerator {
  static async generate(data, platform = "web") {
    if (!data || typeof data !== "object") {
      throw new Error("数据必须是一个对象");
    }

    let result = "";

    // 文件头注释
    result += this.generateHeader();

    // 根据平台选择导出格式
    switch (platform) {
      case "web":
        result += this.generateESModule(data);
        break;
      case "rn":
        result += this.generateCommonJS(data);
        break;
      default:
        result += this.generateESModule(data);
        break;
    }

    return result;
  }

  static generateHeader() {
    const now = new Date().toISOString();
    return `/**
 * Generated by i18n-CLI
 * Created on ${now}
 */

`;
  }

  static generateESModule(data) {
    // ES6 模块格式
    const sortedData = {};
    Object.keys(data)
      .sort()
      .forEach((key) => {
        sortedData[key] = data[key];
      });

    let result = "export default ";
    result += JSON.stringify(sortedData, null, 2);
    result += ";\n";

    return result;
  }

  static generateCommonJS(data) {
    // CommonJS 格式
    const sortedData = {};
    Object.keys(data)
      .sort()
      .forEach((key) => {
        sortedData[key] = data[key];
      });

    let result = "module.exports = ";
    result += JSON.stringify(sortedData, null, 2);
    result += ";\n";

    return result;
  }

  static generateNamedExports(data) {
    // 命名导出格式
    let result = "";

    const sortedKeys = Object.keys(data).sort();

    for (const key of sortedKeys) {
      const value = data[key];
      const safeName = this.makeSafeVariableName(key);
      result += `export const ${safeName} = ${JSON.stringify(value)};\n`;
    }

    // 默认导出
    result += "\nexport default {\n";
    for (const key of sortedKeys) {
      const safeName = this.makeSafeVariableName(key);
      result += `  '${key}': ${safeName},\n`;
    }
    result += "};\n";

    return result;
  }

  static makeSafeVariableName(name) {
    // 将字符串转换为安全的JavaScript变量名
    return name.replace(/[^a-zA-Z0-9_$]/g, "_").replace(/^(\d)/, "_$1"); // 不能以数字开头
  }
}

module.exports = JsGenerator;
